<template>
  <div class="profile-container">
    <div class="profile-header">
      <button class="close-btn" @click="closeProfile">
        <i class="el-icon-close"></i>
      </button>
      <div class="header-background"></div>
      <div class="profile-avatar-area">
        <div class="avatar-container">
          <el-avatar :size="120" :src="typeof userPicture === 'string' ? userPicture : ''" class="user-avatar"></el-avatar>
          <div class="avatar-overlay">
            <label for="uploadAvatar" class="change-avatar-btn">
              <i class="el-icon-camera"></i>
            </label>
            <input id="uploadAvatar" type="file" accept="image/*" @change="handleAvatarChange" style="display: none;" />
          </div>
        </div>
        <h2 class="user-name">{{ userName || '未设置用户名' }}</h2>
      </div>
    </div>

    <div class="profile-body">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="8">
          <el-card class="user-info-card">
            <div slot="header" class="card-header">
              <span><i class="el-icon-user"></i> 个人基本信息</span>
              <el-button type="text" icon="el-icon-edit" @click="showEditDialog">编辑资料</el-button>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="info-label">所属专业</span>
                <span class="info-value">{{ getDeptName(dept_id) || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">账号</span>
                <span class="info-value">{{ userEmail || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">注册时间</span>
                <span class="info-value">{{ userRegisterTime || '未知' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">性别</span>
                <span class="info-value">{{ userSex || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">年龄</span>
                <span class="info-value">{{ userAge || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">国籍</span>
                <span class="info-value">{{ userFrom || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">个人简介</span>
                <span class="info-value">{{ userSelf || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">本月活跃度</span>
                <span class="info-value">
                  <el-tag :type="getActivityLevelType(monthlyActivity)" size="small">
                    {{ formatActivityCount(monthlyActivity) }}
                  </el-tag>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :md="16">
          <el-card class="posts-card">
            <div slot="header" class="card-header">
              <span><i class="el-icon-document"></i> 我的帖子</span>
              <el-button type="text" icon="el-icon-edit" @click="$router.push('/Main/forum/publish')">发布新帖</el-button>
            </div>

            <div v-if="loading" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>

            <div v-else-if="MyTipList.length === 0" class="empty-posts">
              <i class="el-icon-document"></i>
              <p>您还没有发布过帖子</p>
              <el-button type="primary" size="small" @click="$router.push('/Main/forum/publish')">去发布</el-button>
            </div>

            <div v-else class="posts-list">
              <div v-for="post in MyTipList" :key="post.tipId" class="post-item" @click="openDrawer(post.tipId)">
                <div class="post-image">
                  <img v-if="post.tipPictrue" :src="post.tipPictrue" alt="帖子图片" />
                  <div v-else class="image-placeholder">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </div>
                <div class="post-content">
                  <div class="post-title">{{ post.tipTitel }}</div>
                  <div class="post-time">
                    <i class="el-icon-time"></i> {{ formatDate(post.tipTime) }}
                  </div>
                  <div class="post-stats">
                    <span class="stat-item"><i class="el-icon-view"></i> {{ post.tipViews }}</span>
                    <span class="stat-item"><i class="el-icon-chat-dot-round"></i> {{ post.tipComments }}</span>
                    <span class="stat-item"><i class="el-icon-star-on"></i> {{ post.tipGoods }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="pagination-wrapper" v-if="total > pageSize">
              <el-pagination
                :current-page.sync="currentPage"
                :page-size="pageSize"
                layout="prev, pager, next, total"
                :total="total"
                background
                @current-change="handlePageChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog title="编辑个人资料" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" ref="editForm" :rules="editRules" label-width="80px">
        <el-form-item label="用户名" prop="UserName">
          <el-input v-model="editForm.UserName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="dept_id">
          <el-select v-model="editForm.dept_id" placeholder="请选择专业">
            <el-option
              v-for="dept in deptList"
              :key="dept.dept_id"
              :label="dept.dept_name"
              :value="dept.dept_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="UserSex">
          <el-radio-group v-model="editForm.UserSex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="保密">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="UserAge">
          <el-input-number v-model="editForm.UserAge" :min="1" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="国籍" prop="UserFrom">
          <el-input v-model="editForm.UserFrom" placeholder="请输入国籍"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="UserSelf">
          <el-input
            type="textarea"
            v-model="editForm.UserSelf"
            :rows="4"
            placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserInfo" :loading="updateLoading">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {postMyPicture, getMySelf, getMyTip, deptlist, updateUser} from "@/api/api";

export default {
  data() {
    return {
      MyTipList: [],
      userName: '',
      dept_id: '',
      userSex: '',
      userAge: '',
      userRegisterTime: '',
      userEmail: '',
      userFrom: '',
      userSelf: '',
      readerBusy: false,
      loading: false,
      userPicture: null,
      total: 0,
      currentPage: 1,
      pageSize: 4, // 修改为每页显示4个帖子
      monthlyActivity: 0, // 添加本月活跃度数据
      editDialogVisible: false, // 编辑对话框显示状态
      updateLoading: false, // 更新信息的加载状态
      deptList: [], // 专业列表
      editForm: {
        UserName: '',
        dept_id: '',
        UserSex: '',
        UserAge: '',
        UserFrom: '',
        UserSelf: '',
        UserEmail: ''
      },
      editRules: {
        UserName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        UserAge: [
          { type: 'number', message: '年龄必须为数字值', trigger: 'blur' }
        ],
        UserSelf: [
          { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    const savedPage = localStorage.getItem('informationcurrentPage');
    if (savedPage) {
      this.currentPage = parseInt(savedPage, 10);
    }
    this.loading = true;
    this.fetchUserInfo();
    this.initMyTip();
    this.fetchDeptList();
  },
  beforeDestroy() {
    localStorage.setItem('informationcurrentPage', this.currentPage);
  },
  methods: {
    async fetchDeptList() {
      try {
        const response = await deptlist();
        if (response && response.data && response.data.message === "成功") {
          this.deptList = response.data.data;
        }
      } catch (error) {
        console.error("获取专业列表失败：", error);
        this.$message.error('获取专业列表失败');
      }
    },
    getDeptName(deptId) {
      if (!deptId || !this.deptList || this.deptList.length === 0) return '未设置';
      const dept = this.deptList.find(item => item.dept_id === deptId);
      return dept ? dept.dept_name : '未设置';
    },
    showEditDialog() {
      this.editForm = {
        UserName: this.userName,
        dept_id: this.dept_id,
        UserSex: this.userSex,
        UserAge: this.userAge ? parseInt(this.userAge) : '',
        UserFrom: this.userFrom,
        UserSelf: this.userSelf,
        UserEmail: this.userEmail
      };
      this.editDialogVisible = true;
    },
    async updateUserInfo() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          try {
            this.updateLoading = true;
            const response = await updateUser(this.editForm);
            if (response && response.data && response.data.message === "成功") {
              this.$message.success('个人资料更新成功');
              this.editDialogVisible = false;
              await this.fetchUserInfo(); // 重新获取用户信息
            } else {
              this.$message.error('个人资料更新失败');
            }
          } catch (error) {
            console.error("更新用户信息失败：", error);
            this.$message.error('个人资料更新失败');
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
    async initMyTip() {
      try {
        const response = await getMyTip({
          PageNumber: this.currentPage,
          PageSize: this.pageSize,
        });
        if (response && response.data && response.data.message === "成功") {
          this.MyTipList = response.data.data.list;
          this.total = response.data.data.total;
          this.calculateMonthlyActivity(response.data.data.list);
        } else {
          this.$message.error('获取我的帖子列表失败');
        }
      } catch (error) {
        console.error("获取帖子失败：", error);
        this.$message.error('获取我的帖子列表失败');
      } finally {
        this.loading = false;
      }
    },
    calculateMonthlyActivity(posts) {
      const now = new Date();
      const currentMonth = now.getMonth();
      const currentYear = now.getFullYear();

      this.monthlyActivity = posts.filter(post => {
        const postDate = new Date(post.tipTime);
        return postDate.getMonth() === currentMonth &&
               postDate.getFullYear() === currentYear;
      }).length;
    },
    getActivityLevelType(activity) {
      if (activity >= 10) return 'success';
      if (activity >= 5) return 'warning';
      return 'info';
    },
    openDrawer(tipId) {
      this.$router.push({path: '/Main/information/tipdetail', query: {tipId: tipId}});
    },
    async handlePageChange(page) {
      this.loading = true;
      this.currentPage = page;
      try {
        const response = await getMyTip({
          PageNumber: this.currentPage,
          PageSize: this.pageSize,
        });
        if (response && response.data && response.data.message === "成功") {
          this.MyTipList = response.data.data.list;
          this.total = response.data.data.total;
        } else {
          this.$message.error('获取我的帖子列表失败');
        }
      } catch (error) {
        console.error("获取帖子失败：", error);
        this.$message.error('获取我的帖子列表失败');
      } finally {
        this.loading = false;
      }
    },
    closeProfile() {
      this.$router.go(-1);
    },
    async fetchUserInfo() {
      try {
        const response = await getMySelf();
        if (response && response.data && response.data.message === "成功") {
          this.$store.state.me = response.data.data;
          this.userName = this.$store.state.me.userName;
          this.dept_id = this.$store.state.me.dept_id;
          this.userSex = this.$store.state.me.userSex;
          this.userAge = this.$store.state.me.userAge;
          this.userRegisterTime = this.$store.state.me.userRegisterTime;
          this.userEmail = this.$store.state.me.userEmail;
          this.userFrom = this.$store.state.me.userFrom;
          this.userPicture = this.$store.state.me.userPicture;
          this.userSelf = this.$store.state.me.userSelf;
          this.UserRank= this.$store.state.me.UserRank;
        }
      } catch (error) {
        console.error("获取用户信息失败：" + error);
        this.$message.error('获取用户信息失败');
      }
    },
    async handleAvatarChange(event) {
      const file = event.target.files[0];
      if (file && !this.readerBusy) {
        try {
          this.loading = true;
          this.readerBusy = true;

          const reader = new FileReader();
          reader.readAsDataURL(file);

          reader.onload = async () => {
            const formData = new FormData();
            formData.append('Picture', file);

            try {
              const response = await postMyPicture(formData);
              if (response.data.message === "成功") {
                this.$message.success('头像上传成功');
                await this.fetchUserInfo();
              } else {
                this.$message.error('头像上传失败');
              }
            } catch (uploadError) {
              console.error("发生错误：" + uploadError);
              this.$message.error('头像上传失败');
            }

            this.readerBusy = false;
          };

          reader.onerror = () => {
            console.error('File read error');
            this.readerBusy = false;
            this.$message.error('文件读取错误');
          };

        } catch (error) {
          console.error("发生错误：" + error);
          this.readerBusy = false;
        } finally {
          this.loading = false;
        }
      }
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const now = new Date();
      const diffTime = Math.abs(now - date);
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

      if (diffDays === 0) {
        return '今天';
      } else if (diffDays === 1) {
        return '昨天';
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else {
        return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      }
    },
    formatActivityCount(count) {
      if (count >= 4) {
        return '4+';
      }
      return count + ' 帖';
    },
  }
};
</script>

<style scoped>
.profile-container {
  padding: 0;
  position: relative;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.profile-header {
  position: relative;
  height: 220px;
  text-align: center;
  margin-bottom: 80px;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #1a4b6e 0%, #2c7a7b 100%);
  z-index: 0;
}

.profile-avatar-area {
  position: relative;
  z-index: 1;
  padding-top: 40px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.user-avatar {
  border: 5px solid #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  background-color: #fff;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-overlay:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.change-avatar-btn {
  color: #fff;
  cursor: pointer;
}

.user-name {
  color: #fff;
  margin-top: 15px;
  font-size: 24px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  color: #fff;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.4);
}

.profile-body {
  padding: 0 20px 30px;
}

.user-info-card, .posts-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  background-color: #fff;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  font-weight: 600;
}

.card-header i {
  margin-right: 5px;
}

.info-list {
  padding: 0;
}

.info-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f3f3f3;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  width: 80px;
  color: #909399;
  flex-shrink: 0;
}

.info-value {
  flex-grow: 1;
  color: #303133;
  font-weight: 500;
  word-break: break-word;
}

.empty-posts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-posts i {
  font-size: 40px;
  margin-bottom: 15px;
  opacity: 0.5;
}

.empty-posts p {
  margin-bottom: 15px;
}

.posts-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.post-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.post-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.post-image {
  height: 140px;
  overflow: hidden;
}

.post-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.post-item:hover .post-image img {
  transform: scale(1.05);
}

.post-content {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #303133;
  line-height: 1.4;
  flex-grow: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.post-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.post-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item i {
  margin-right: 4px;
}

.pagination-wrapper {
  margin-top: 30px;
  padding: 20px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

.loading-container {
  padding: 20px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.image-placeholder i {
  font-size: 32px;
}

@media (max-width: 768px) {
  .posts-list {
    grid-template-columns: 1fr;
  }

  .profile-header {
    height: 180px;
    margin-bottom: 60px;
  }

  .user-avatar {
    width: 100px;
    height: 100px;
  }

  .profile-body {
    padding: 0 10px 20px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    padding: 15px 0;
  }
}
</style>
